package com.lin.healthmanagement.controller;

import com.lin.healthmanagement.controller.code.Code;
import com.lin.healthmanagement.controller.code.Message;
import com.lin.healthmanagement.controller.exception.BusinessException;
import com.lin.healthmanagement.controller.result.Result;
import com.lin.healthmanagement.dao.UserDao;
import com.lin.healthmanagement.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;


@RestController
public class LoginController {

    @Autowired
    UserDao userDao;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        // 1. 声明变量（提升作用域到方法内）
        User us = null;
        Integer code = Code.SYSTEM_BUSY;
        String msg = Message.Error;
        try {
            // 2. 参数校验（补充：避免空指针或无效参数）
            if (user == null || user.getUserName() == null || user.getPassword() == null) {
                throw new BusinessException(Code.PARAM_ERR, "用户名或密码不能为空");
            }
            // 3. 调用DAO查询用户
            us = userDao.getUserByMessage(user.getUserName(), user.getPassword());
            // 4. 根据查询结果设置状态码和消息
            code = us != null ? Code.GET_OK : Code.GET_ERR;
            msg = us != null ? Message.ok : Message.fail;
        } catch (BusinessException e) {
            // 捕获自定义业务异常（如参数错误），直接抛出
            throw e;
        } catch (Exception e) {
            // 捕获其他异常（如数据库异常），转换为系统忙异常
            throw e; // 建议携带原异常信息，便于排查
        }
        // 5. 返回结果（此时可访问所有变量）
        return new Result(code, msg, us);
    }



}
